package servlet;

import dao.CartDAO;
import pojo.Cart;
import utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/cart")
public class CartServlet extends BaseServlet {

    private void addCartItem(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        int userId = Integer.parseInt(request.getParameter("userId"));
        int productId = Integer.parseInt(request.getParameter("productId"));
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        String img = request.getParameter("img");

        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);
        cart.setQuantity(quantity);
        cart.setImg(img);
        CartDAO.addCartItem(cart);
        sendJsonResponse(response, new ApiResult(200, "加入购物车成功", null));
    }

    // 删除购物车项
    public void deleteCartItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int cartId = Integer.parseInt(req.getParameter("cartId"));

        try {
            CartDAO.deleteCartItem(cartId);
            sendJsonResponse(resp, new ApiResult(200, "购物车项删除成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "购物车项删除失败", e.getMessage()));
        }
    }

    // 根据用户ID查询购物车项
    public void getCartItemsByUserId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = Integer.parseInt(req.getParameter("userId"));

        try {
            List<Cart> cartItems = CartDAO.getCartItemsByUserId(userId);
            sendJsonResponse(resp, new ApiResult(200, "根据用户ID查询购物车项成功", cartItems));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "根据用户ID查询购物车项失败", e.getMessage()));
        }
    }

    // 获取所有购物车项
    public void getAllCartItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Cart> cartItems = CartDAO.getAllCartItems();
            sendJsonResponse(resp, new ApiResult(200, "获取所有购物车项成功", cartItems));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "获取所有购物车项失败", e.getMessage()));
        }
    }
}
